<template>
  <div class="page-wrap">
    <div class="page-header">
      <div class="page-title">
        新增调拨
        <el-tag type="success" effect="plain" class="title-tag">Create Allocation</el-tag>
      </div>
      <div class="page-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">保存</el-button>
      </div>
    </div>

    <el-card shadow="never">
      <el-form :model="form" label-width="100px" :rules="dynamicRules" ref="formRef">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="调拨类型" prop="transferType">
              <el-select v-model="form.transferType" placeholder="选择类型">
                <el-option label="普通调拨" value="普通调拨" />
                <el-option label="紧急调拨" value="紧急调拨" />
                <el-option label="临时调拨" value="临时调拨" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker v-model="form.applyDate" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="选择日期时间" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调出仓库" prop="fromWarehouseId">
              <el-select v-model="form.fromWarehouseId" placeholder="选择调出仓库" filterable>
                <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调入仓库" prop="toWarehouseId">
              <el-select v-model="form.toWarehouseId" placeholder="选择调入仓库" filterable>
                <el-option v-for="w in warehouses" :key="w.id" :label="w.name" :value="w.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="经办人" prop="handlerId">
              <el-input v-model="form.handlerName" placeholder="输入经办人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人" prop="applicantId">
              <el-input v-model="form.applicantName" placeholder="输入申请人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input type="textarea" rows="2" v-model="form.remark" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="24">
            <el-form-item>
              <el-checkbox v-model="form.skipValidation">跳过所有验证（允许创建任意调拨单）</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never" style="margin-top:12px;">
      <div style="margin-bottom:8px; display:flex; gap:8px;">
        <el-button type="primary" @click="addRow">新增行</el-button>
        <el-button type="danger" :disabled="!selectedRowKeys.length" @click="removeSelected">移除选中</el-button>
      </div>
      <el-table :data="form.items" border stripe height="420" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column label="商品名称" min-width="180">
          <template #default="{ row }">
            <el-input v-model="row.productName" placeholder="输入或选择商品" />
          </template>
        </el-table-column>
        <el-table-column label="商品编号" width="140">
          <template #default="{ row }">
            <el-input v-model="row.productNo" />
          </template>
        </el-table-column>
        <el-table-column label="规格" width="120">
          <template #default="{ row }">
            <el-input v-model="row.spec" />
          </template>
        </el-table-column>
         <el-table-column label="单位" width="90">
           <template #default="{ row }">
             <el-input v-model="row.unit" />
           </template>
         </el-table-column>
         <el-table-column label="调出库位" width="120">
           <template #default="{ row }">
             <el-select v-model="row.fromLocationId" placeholder="选择库位" size="small">
               <el-option 
                 v-for="loc in locations.filter(l => l.warehouseId === form.fromWarehouseId)" 
                 :key="loc.id" 
                 :label="loc.name" 
                 :value="loc.id" 
               />
             </el-select>
           </template>
         </el-table-column>
         <el-table-column label="调入库位" width="120">
           <template #default="{ row }">
             <el-select v-model="row.toLocationId" placeholder="选择库位" size="small">
               <el-option 
                 v-for="loc in locations.filter(l => l.warehouseId === form.toWarehouseId)" 
                 :key="loc.id" 
                 :label="loc.name" 
                 :value="loc.id" 
               />
             </el-select>
           </template>
         </el-table-column>
         <el-table-column label="调出可用库存" width="120" align="right">
           <template #default="{ row }">{{ formatNumber(row.outWarehouseStock) }}</template>
         </el-table-column>
        <el-table-column label="调入仓库存" width="120" align="right">
          <template #default="{ row }">{{ formatNumber(row.inWarehouseStock) }}</template>
        </el-table-column>
        <el-table-column label="调拨数量" width="120" align="right">
          <template #default="{ row }">
            <el-input-number v-model="row.transferQty" :min="0" :step="1" />
          </template>
        </el-table-column>
        <el-table-column label="入库单价" width="120" align="right">
          <template #default="{ row }">
            <el-input-number v-model="row.inUnitPrice" :min="0" :step="0.01" />
          </template>
        </el-table-column>
        <el-table-column label="调拨金额" width="120" align="right">
          <template #default="{ row }">{{ formatNumber(row.transferAmount) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ $index }">
            <el-button size="small" text type="danger" @click="removeRow($index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:8px; text-align:right;">
        <span>合计：数量 {{ formatNumber(totalQty) }} ，金额 {{ formatNumber(totalAmount) }}</span>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ReadClients ,WriteClients} from '../../Urls/AxiosHelper'

const Read = ReadClients[0]
const Write = WriteClients[0]
const router = useRouter()

interface Warehouse { id: number; name: string }

interface TransferItemRow {
  productId?: number
  productNo?: string
  productName?: string
  spec?: string
  unit?: string
  inWarehouseStock?: number
  outWarehouseStock?: number
  fromLocationId?: number
  toLocationId?: number
  transferQty: number
  inUnitPrice: number
  transferAmount: number
}

interface CreateTransferPayload {
  transferType: string
  applyDate: string
  fromWarehouseId: number
  toWarehouseId: number
  handlerName?: string | null
  applicantName?: string | null
  remark?: string | null
  skipValidation?: boolean
  lines: Array<{
    productId: number
    productName: string
    productNo: string
    specification: string
    unit: string
    fromLocationId: number
    toLocationId: number
    reqQty: number
    unitPrice: number
    fromWarehouseStock: number
    toWarehouseStock: number
  }>
}

const warehouses = ref<Warehouse[]>([
  { id: 1, name: '成品仓库一' },
  { id: 2, name: '成品仓库二' },
  { id: 3, name: '原料仓库一' },
  { id: 4, name: '原料仓库二' },
])

// 模拟库位数据
const locations = ref([
  { id: 1, name: 'A区-01', warehouseId: 1 },
  { id: 2, name: 'A区-02', warehouseId: 1 },
  { id: 3, name: 'B区-01', warehouseId: 2 },
  { id: 4, name: 'B区-02', warehouseId: 2 },
  { id: 5, name: 'C区-01', warehouseId: 3 },
  { id: 6, name: 'C区-02', warehouseId: 3 },
  { id: 7, name: 'D区-01', warehouseId: 4 },
  { id: 8, name: 'D区-02', warehouseId: 4 },
])

const formRef = ref<FormInstance>()
const submitting = ref(false)
const form = reactive({
  transferType: '普通调拨',
  applyDate: new Date().toISOString().slice(0,19),
  fromWarehouseId: undefined as number | undefined,
  toWarehouseId: undefined as number | undefined,
  handlerId: undefined as number | undefined,
  handlerName: '',
  applicantId: undefined as number | undefined,
  applicantName: '',
  remark: '',
  skipValidation: true, // 默认跳过验证
  items: [] as TransferItemRow[],
})

const rules: FormRules = {
  transferType: [{ required: true, message: '请选择调拨类型', trigger: 'change' }],
  applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  fromWarehouseId: [{ required: true, message: '请选择调出仓库', trigger: 'change' }],
  toWarehouseId: [{ required: true, message: '请选择调入仓库', trigger: 'change' }],
}

// 动态验证规则
const dynamicRules = computed(() => {
  if(form.skipValidation){
    return {} // 跳过验证时返回空规则
  }
  return rules
})

const selectedRowKeys = ref<any[]>([])

const totalQty = computed(() => form.items.reduce((s, r) => s + (Number(r.transferQty) || 0), 0))
const totalAmount = computed(() => form.items.reduce((s, r) => s + (Number(r.transferAmount) || 0), 0))

function addRow(){
  form.items.push({ 
    transferQty: 0, 
    inUnitPrice: 0, 
    transferAmount: 0,
    fromLocationId: 1, // 默认库位
    toLocationId: 1
  })
}

function removeRow(index: number){
  form.items.splice(index,1)
}

function onSelectionChange(rows: TransferItemRow[]){
  selectedRowKeys.value = rows
}

function removeSelected(){
  if(!selectedRowKeys.value.length) return
  form.items = form.items.filter(r => !selectedRowKeys.value.includes(r))
}

function formatNumber(n: number | string){
  const num = Number(n ?? 0)
  return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(num)
}

async function handleSubmit(){
  if(!formRef.value) return
  
  // 如果跳过验证，直接提交；否则进行表单验证
  if(!form.skipValidation){
    await formRef.value.validate(async (valid) => {
      if(!valid) return
      await submitData()
    })
  } else {
    await submitData()
  }
}

async function submitData(){
  if(!form.items.length){
    ElMessage.warning('请至少添加一条明细')
    return
  }
    
  // 如果跳过验证，只做最基本的检查
  if(!form.skipValidation){
    // 验证调出仓库和调入仓库不能相同
    if(form.fromWarehouseId === form.toWarehouseId){
      ElMessage.error('调出仓库和调入仓库不能相同')
      return
    }
    
    // 验证明细项
    for(let i = 0; i < form.items.length; i++){
      const item = form.items[i]
      if(!item.productName || !item.productName.trim()){
        ElMessage.error(`第${i+1}行商品名称不能为空`)
        return
      }
      if(!item.transferQty || item.transferQty <= 0){
        ElMessage.error(`第${i+1}行调拨数量必须大于0`)
        return
      }
      if(!item.fromLocationId){
        ElMessage.error(`第${i+1}行调出库位不能为空`)
        return
      }
      if(!item.toLocationId){
        ElMessage.error(`第${i+1}行调入库位不能为空`)
        return
      }
    }
  }
  
  // 计算金额
  form.items.forEach(r => r.transferAmount = (Number(r.transferQty)||0) * (Number(r.inUnitPrice)||0))

  // 确保日期格式正确
  const applyDate = new Date(form.applyDate).toISOString()
  
  const payload = {
    transferType: form.transferType,
    applyDate: applyDate,
    fromWarehouseId: form.fromWarehouseId || 1, // 提供默认值
    toWarehouseId: form.toWarehouseId || 1, // 提供默认值
    handlerName: form.handlerName || null,
    applicantName: form.applicantName || null,
    remark: form.remark || null,
    skipValidation: form.skipValidation, // 添加跳过验证参数
    lines: form.items.map(it => ({
      productId: it.productId || 0,
      productName: it.productName || '',
      productNo: it.productNo || '',
      specification: it.spec || '',
      unit: it.unit || '',
      fromLocationId: it.fromLocationId || 1,
      toLocationId: it.toLocationId || 1,
      reqQty: Number(it.transferQty) || 0,
      unitPrice: Number(it.inUnitPrice) || 0,
      fromWarehouseStock: Number(it.outWarehouseStock) || 0,
      toWarehouseStock: Number(it.inWarehouseStock) || 0
    }))
  }

  console.log('提交数据:', JSON.stringify(payload, null, 2))

  submitting.value = true
  try{
    const res = await Write.post('/write/api/Allocation/CreateAllocation', payload)
    console.log('响应数据:', res.data)
    if(res.data?.code === 200){
      ElMessage.success('创建成功')
      router.back()
    }else{
      ElMessage.error(res.data?.message || '创建失败')
    }
  }catch(e:any){
    console.error('请求错误:', e)
    console.error('错误响应:', e.response?.data)
    console.error('错误状态:', e.response?.status)
    console.error('错误头:', e.response?.headers)
    
    // 尝试解析更详细的错误信息
    let errorMessage = '创建失败'
    if(e.response?.data?.message){
      errorMessage = e.response.data.message
    } else if(e.response?.data?.errors){
      // 处理验证错误
      const errors = e.response.data.errors
      const errorMessages = Object.keys(errors).map(key => `${key}: ${errors[key].join(', ')}`)
      errorMessage = errorMessages.join('; ')
    } else if(e.response?.data?.title){
      errorMessage = e.response.data.title
    }
    
    ElMessage.error(errorMessage)
  }finally{
    submitting.value = false
  }
}

function handleCancel(){
  router.back()
}
</script>

<style scoped>
.page-wrap{ display:flex; flex-direction:column; gap:12px; }
.page-header{ display:flex; align-items:center; justify-content:space-between; }
.page-title{ font-size:18px; font-weight:600; display:flex; align-items:center; gap:8px; }
.title-tag{ vertical-align: middle; }
.page-actions{ display:flex; gap:8px; }
</style>
